// ==UserScript==
// @name     jwgl验证码
// @include  http://10.10.10.71/default2.aspx
// @require	 https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
// @version  1
// @grant    none
// ==/UserScript==

(function() {
    var config = {
        host : "api.xf-yun.com",
        path : "/v1/private/sf8e6aca1",
        APPID : "",
        apiSecret : "",
        apiKey : "",
        imageId : 'icode', // 验证码id
        codeId : 'txtSecretCode',  // 验证码输入框id
    }

    // 使用 hmac sha256 加密
    function sign(msg) {
        let cmsg = CryptoJS.HmacSHA256(msg, config.apiSecret);
        console.log(cmsg.toString(CryptoJS.enc.Base64));
        return cmsg.toString(CryptoJS.enc.Base64);
    }

    // 构造请求url
    function buildRequetUrl() {
        // signature的原始字段(signature_origin)规则如下。
        // signature原始字段由 host，date，request-line三个参数按照格式拼接成，
        // 拼接的格式为(\n为换行符,’:’后面有一个空格)：
        // host: $host\ndate: $date\n$request-line
        const date = (new Date()).toUTCString();
        // const date = "Wed, 18 Oct 2023 02:08:45 GMT";
        var so1 = "host: " + config.host + "\n" +
            "date: " + date + "\n" +
            "POST " + config.path + " HTTP/1.1";
        console.log(so1);

        var authorization = 'api_key="' + config.apiKey + '", algorithm="hmac-sha256", headers="host date request-line", signature="' + sign(so1) + '"';
        console.log(authorization);

        var authBase = btoa(authorization);
        console.log(authBase);

        var url = 'https://' + config.host + config.path + '?authorization=' + encodeURIComponent(authBase) + '&date=' + encodeURIComponent(date) + '&host=' + encodeURIComponent(config.host);
        console.log(url);
        return url;
    }

    // 准备请求参数
    function buildParam() {
        var img = getBase64Image();
        console.log(img);
        var body = '{' +
            '  "header": {' +
            '    "app_id": "' + config.APPID + '",' +
            '    "status": 3' +
            '  },' +
            '  "parameter": {' +
            '    "sf8e6aca1": {' +
            '      "category": "ch_en_public_cloud",' +
            '      "result": {' +
            '        "encoding": "utf8",' +
            '        "compress": "raw",' +
            '        "format": "json"' +
            '      }' +
            '    }' +
            '  },' +
            '  "payload": {' +
            '    "sf8e6aca1_data_1": {' +
            '      "encoding": "jpg",' +
            '      "status": 3,' +
            '      "image": "' + img + '"' +
            '    }' +
            '  }' +
            '}'
        var param = {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: body
        };
        console.log(param);
        return param;
    }

    // function getImage() {
    //     return "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyAMgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0EU4U0U8UAULnXdJstRTT7rUbaC7dA6RSyBSwJIGM9eQa0lIIBByD3Fcj4n+Heh+K7k3d4LiK8KhfOhk7D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46YrW8XfD//AISlLC3laNUt0AZo2MfPTIGGBAySFwOv3gOCAeceDvH/AIe8F6BFEti8+szKTcXAVHCkn5fmzuIAAJUfmDXo3hX4m2Wsao2n3sgglcbovOQxF/lXhUOTj7xyT+g4n0z4X6HaJvliPmyczqojKv6DIjXAx2UKPatBfAOlQXYurEGzlRt0f2eNFxx8oyVJAB54xnODkcUAYPxN8ZNo1rLZRv5TSII1bO1yWPzMucfdUEZ7s4/u84Hw8udAt0l8R69qtn9olDSYZsGMtMX+7yeNqkem5h6V13xF+Hp8Z2kUlvc/Z7qIcgjcJAAcLk/d5xyMZ75wMcRpf7P0rTqdT1XEGzlYh8wYr27cMf09+ADtdP8AjBoGreJYdH0+K5mEhINwVCr2xgHk8+1eK+MtPbSfiaBrySNZNco8pwcNGWzIF9slsfWve/Dvwu8LeHJ0ubWxMt1G+9JpnLMpByMduOB+H1rY8T+D9G8X2H2XVbYPt+5MmBJH/utj/wCtQB5R4/8AAfga1+H9xreiGNLoRo1u6XJIlG5QflzjO3PTvUP7OmpQQXGu2M0yI83kPErMAWI3ggevVa6Sw+Afh+1ml+0395dQMpCRMQu0nODx1Iqr4b+A66H4ntNWfX3eOznWaKJIMM+05wzE8ehwKAPZhTxTRThQA4U8U0U4UAOFFKKKAOGFOFFFADxThRRQA8U4UUUAOFPFFFADhThRRQA8U4UUUAOFPFFFADhTxRRQA4U4UUUAPFOFFFADhTxRRQA4U8UUUAOFFFFAH//Z";
    // }

    // 图像转base64,
    // https://stackoverflow.com/questions/934012/get-image-data-url-in-javascript
    function getBase64Image() {
        var img = document.getElementById(config.imageId);
        console.log(img);
        // Create an empty canvas element
        var canvas = document.createElement("canvas");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;

        // Copy the image contents to the canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        // Get the data-URL formatted image
        // Firefox supports PNG and JPEG. You could check img.src to
        // guess the original format, but be aware the using "image/jpg"
        // will re-encode the image.
        var dataURL = canvas.toDataURL("image/jpeg");
        // var dataURL = canvas.toDataURL();
        var imgBase = dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
        console.log("image base64");
        console.log(dataURL)

        return imgBase;
    }

    function onSuccess(data) {
        // console.log(data.payload.result.text);
        var result = JSON.parse(atob(data.payload.result.text));
        console.log(result);
        var lines = result.pages[0].lines;
        var code = '';
        for (var i=0; i<lines.length; i++) {
            if (lines[i].words) {
                code += lines[i].words[0].content;
            }

        }
        console.log(code);
        var icode = document.getElementById(config.codeId);
        icode.value = code;
    }

    function getCode() {
        var url = buildRequetUrl();
        var param = buildParam();
        fetch(url, param).then(function (response) {
            // console.log(response);
            return response.json();
        }).then(function (data) {
            console.log(data);
            if (data.header && data.header.code == 0) {
                console.log('success');
                onSuccess(data);
            } else {
                console.log('failed');
            }
        }).catch(function (e) {
            console.log("Oops, error");
        });
    }

    // buildParam();
    setTimeout(getCode,500);
    //getCode();
}());